import React from 'react'
// ===================================================================== Temp
// ===================================================================== Image
import gbImg 	from '@img/quality/gb.png'
import jgImg 	from '@img/quality/jg.png'
import jjImg 	from '@img/quality/jj.png'
// ===================================================================== Declare
const { $Lazy, $fn, $http } = window
// ===================================================================== Lazy
const $cache 			= $Lazy.file(()=>import('#private/cache-api'))
const Form 				= $Lazy.hook(()=>import('@antd/form/layout/form'))
const FormItem 			= $Lazy.load(()=>import('@antd/form/layout/item'))
const Modal 			= $Lazy.state(()=>import('@antd/modal'))
const Input 			= $Lazy.load(()=>import('@antd/form/input'))
// const Button 			= $Lazy.load(()=>import('@antd/button'))
const Checkbox 			= $Lazy.load(()=>import('@antd/form/checkbox'))
const SplitDom			= $Lazy.hook(()=>import('../cpt/split-dom'))
const Radio 			= $Lazy.load(()=>import('./rule-cpt/radio'))
// const CheckboxGroup 	= $Lazy.load(()=>import('@antd/form/checkboxGroup'))
// const DatePicker 		= $Lazy.load(()=>import('@antd/form/datePicker'))
// ===================================================================== component
// ===================================================================== data
const ruleRadioData = [{name: '', value: '-1'}, {name: '', value: '1'}, {name: '', value: '2'}]
		
class Index extends React.Component{
	state = {
		data: [],
		formData: {},
		ruleData: [],
		tabIndex: 0,
		selectedIndex: 0,
		selectedRow: {},
		imgUrl: '',
		analyte_name: '',
		levelsData: []
	}
	
	submit = {}
	
	open = ({uuid, analyte_name}) => {
		this.uuid = uuid
		this.setState({analyte_name, tabIndex: 0})
		this.fetch()
		this.modalRef.open()
	}
	
	componentDidMount() {
		this.getImages()
	}
	
	getImages = () => {
		$cache.then( async f => {
			const data = await f.getCache({ api:'qc-rule/tpl' } )
			this.setState({ruleData: data, selectedRow: data[0]})
		})
	}
	
	fetch = () => $http.pull(null,'qc-rule/info', { param: {test_id: this.uuid} }).then(data => {
		const levelsData = []
		for (let i = 1; i <= 9; i++) {
			levelsData.push({name1: `level${i}_enabled`, name2: `level${i}_decimal_digits`, name3: `level${i}_rule_pn`, disabled: true, value: false})
		}
		data.levels.forEach(v => {
			levelsData[v -1].disabled = false
			levelsData[v -1].value = true
		})
		this.form.setFieldsValue(data)
		this.setState({formData: data, imgUrl: this.state.selectedRow.img[0], levelsData})
	})

	switch = index => this.setState({tabIndex: index})

	onSubmit = values => $http.submit(null, 'qc-rule/set', { param: {...values, test_id: this.uuid} }).then(() => {
		$fn.msg.success('更新规则成功')
		this.modalRef.close()
	})
	
	getImg = name => {
		const { formData } = this.state
		let url
		switch(formData[name]){
			case '-1':
				url = jjImg
				break
			case '1':
				url = jgImg
				break
			default:
				url = gbImg
		}
		return url
	}
	
	render(){
		const { ruleData, formData, tabIndex, analyte_name, selectedIndex, selectedRow, imgUrl, levelsData } = this.state
		return <>
			<Modal
				title	= {`设置-（${analyte_name}）`}
				width 	= {700}
				height  = {780}
				okText	= '确定'
				noText 	= '取消'
				onRef	= { ref => this.modalRef = ref }
				isFullScroll
				onOk	= { () => this.form.submit() }
				close	= { () => this.form.resetFields() }
			>
				<Form className='h fv' style={{paddingBottom: 15}} dir='x' init={form => this.form = form} onSubmit={this.onSubmit}>
					<div className='fxmc'>
						<div className='rel pb5'>
							<span className='mlr15 cp tab-lable' style={{color: tabIndex ? '' : '#088194'}} onClick={() => this.switch(0)}>规则</span>
							<span className='mlr15 cp tab-lable' style={{color: tabIndex ? '#088194' : ''}} onClick={() => this.switch(1)}>设置</span>
							<div className='abs' style={{width: 28, height: 2, background: '#088194', left: tabIndex ? 73 : 15, bottom: 0, transition: 'all 0.25s'}}></div>
						</div>
					</div>
					<div className='ex' style={{display: tabIndex ? 'none' : 'flex'}}>
						{ formData?.result_type === '2' ? <div className='fv ex'>
								<SplitDom label='定性失控' />
								{levelsData.map((v, i) => <div key={i} className='mtb5 fx' style={{width: 220}}>
									<span className='mr10'>水平{i + 1}：</span>
									<FormItem name={v.name3} noStyle={true}>
										<Radio disabled={v.disabled} data={[{name: '阴性(N)', value: 'N'}, {name: '阳性(P)', value: 'P'}]} />
									</FormItem>
								</div>)}
						</div> : <>
							<div className='fv ex mr30'>
								<SplitDom label='SPC规则' />
								<div className='fxm tc plr10 mt10'>
									<span style={{width: '32%'}}>规则</span>
									<span style={{width: '17%'}}>状态</span>
									<span style={{width: '17%'}}>拒绝</span>
									<span style={{width: '17%'}}>警告</span>
									<span style={{width: '17%'}}>关闭</span>
								</div>
								<div className='ex p10' style={{border: '1px solid #eee'}}>
									{ruleData.map((v, i) => <div key={i} style={{height: 27, lineHeight: '27px'}} className='fxm tc mtb5'>
										<div style={{width: '32%'}} className='fx xc'>
											<span style={{width: 75, backgroundColor: selectedIndex === i ? '#208FA0' : '#F0F0F0', color: '#000'}} className='r5px cp' onClick={() => this.setState({selectedIndex: i, selectedRow: v, imgUrl: v.img[+formData[v.field + '_same_analyte'] ? 0 : 1]}) }>{v.rule}</span>
										</div>
										<div style={{width: '17%'}} className='fx xc'>
											<img src={this.getImg(v.field)} alt='' />
										</div>
										<div className='ex fx'>
											<FormItem name={v.field} className='ex fx'>
												<Radio data={ruleRadioData} onChanged={({value}) => this.setState({formData: {...formData, [v.field]: value}})} />
											</FormItem>
										</div>
									</div>)}
								</div>
							</div>
							<div className='ex fv'>
								<SplitDom label='规则应用' />
								{ruleData.map((v, i) => <div key={i} className='fm mt10' style={{height: 50, display: i === selectedIndex ? 'flex' : 'none'}}>
									<FormItem name={v.field + '_same_analyte'} noStyle={true}>
										<Radio className='fm' onChanged={({value}) => this.setState({imgUrl: selectedRow.img[+value ? 0 : 1]})} disabled={selectedRow.img?.length === 1 ? true : false} data={[{name: '同一控制品内', value: '1'}, {name: '不同控制品内', value: '0'}]} />
									</FormItem>
								</div>)}
								<div className='mtb10' style={{height: 240}}>
									<img src={imgUrl} className='wh' alt='' />
								</div>
								<div className='ex mlr10'>
									<span>{selectedRow.tip}</span>
								</div>
								{/*<div className='plr10 fxc mb15'>
									<Button className='mr15 ex' ghost disabled={formData.enabled === '1' ? true : false} onClick={() => $http.submit(null, 'qc-rule/on', { param:{lot_id: this.uuid} }).then(() => {
										$fn.msg.success('启用规则成功')
										this.fetch()
									})} size='middle' type='primary'>启用 SPC 规则</Button>
									<Button className='ex' disabled={formData.enabled === '1' ? false : true} onClick={() => $http.submit(null, 'qc-rule/off', { param:{lot_id: this.uuid} }).then(() => {
										$fn.msg.success('禁用规则成功')
										this.fetch()
									})} size='middle' type='primary'>禁用 SPC 规则</Button>
								</div>
								<Button className='mlr10' onClick={() => {}} size='middle' type='primary'>Set as default SPC rules</Button>
								<div className='mlr10 mt15'>
									<FormItem name=''>
										<Checkbox isNumber label='应用到所有实验号' onChanged={ () => {} } />
									</FormItem>
								</div>*/}
							</div>
						</> }
					</div>
					<div className='ex' style={{display: tabIndex ? 'flex' : 'none'}}>
						<div className='fv ex'>
							<SplitDom label='使用中的水平' />
							<div className='p10 fx'>
								{levelsData.map((v, i) => <FormItem key={i} name={v.name1} style={{marginRight: 15}}>
									<Checkbox disabled={v.disabled} name={i} onChanged={({name}) => {
										let index = 0
										levelsData[name].value = !levelsData[name].value
										levelsData.forEach(v => v.value && index++)
										if (index.toString() === formData.level) {
											levelsData.forEach(v => {
												if (!v.value) v.disabled = true
											})
										} else {
											levelsData.forEach(v => {
												if (!v.value) v.disabled = false
											})
										}
										this.setState({levelsData})
									}} isNumber label={i + 1} />
								</FormItem>)}
							</div>
							{ formData.result_type === '2' ? null : <><SplitDom label='小数位数' />
							<div className='fx fw'>
								{levelsData.map((v, i) => <div key={i} className='fxm bscb plr15 pt10 pb10' style={{width: 100}}>
									<span>水平{i + 1}：</span>
									<FormItem name={v.name2} noStyle={true}>
										<Input disabled={v.disabled} mode='number' minValue={0} />
									</FormItem>
								</div>)}
							</div></> }
						</div>
					</div>
				</Form>
			</Modal>
		</>
	}
}

export default Index